package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.form.shopping.CartForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Map;

import static com.mall.user.intercepter.TokenIntercepter.USER_INFO_KEY;


@RestController
@Slf4j
@RequestMapping("shopping")
public class CartController {

    @Reference(timeout = 3000, check = false)
    ICartService service;

    /**
     * 获取购物车商品信息
     *
     * @return
     */
    @GetMapping("carts")
    public ResponseData getCartListInfo(HttpServletRequest request) {
        CartListByIdRequest cartListByIdRequest = new CartListByIdRequest();


        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        String uid = object.get("uid").toString();
        Long userId = Long.parseLong(uid);
//        Long userId = Long.parseLong(object.get("uid").toString());

        cartListByIdRequest.setUserId(userId);
        CartListByIdResponse response = service.getCartListById(cartListByIdRequest);

        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMessage("success");
        responseData.setSuccess(true);
        responseData.setTimestamp(System.currentTimeMillis());
        responseData.setResult(response.getCartProductDtos());
        return responseData;
    }

    /**
     * 添加商品到购物车
     *
     * @return
     */
    @PostMapping("carts")
    public ResponseData addToCart(@RequestBody CartForm cartForm) {
        //构造请求参数
        AddCartRequest cartRequest = new AddCartRequest();
        cartRequest.setUserId(cartForm.getUserId());
        cartRequest.setItemId(cartForm.getProductId());
        cartRequest.setNum(cartForm.getProductNum());

        AddCartResponse addCartResponse = service.addToCart(cartRequest);
        if (!addCartResponse.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            //操作失败
            return new ResponseUtil().setErrorMsg(addCartResponse.getMsg());
        }
        ResponseData responseData = new ResponseData<String>();
        responseData.setCode(200);
        responseData.setMessage(addCartResponse.getMsg());
        responseData.setResult("成功");
        responseData.setSuccess(true);
        responseData.setTimestamp(System.currentTimeMillis());
        return responseData;
    }

    @PutMapping("carts")
    public ResponseData updateCartInfo(@RequestBody UpdateCartBO bo) {
        UpdateCartNumRequest cartNumRequest = new UpdateCartNumRequest();
        cartNumRequest.setNum(bo.getProductNum());
        cartNumRequest.setChecked(bo.getChecked());
        cartNumRequest.setItemId(bo.getProductId());
        cartNumRequest.setUserId(bo.getUserId());

        // 如果redis中没有该购物车信息，返回的为null
        @Nullable
        UpdateCartNumResponse updateCartNumResponse = service.updateCartNum(cartNumRequest);

        ResponseData<String> responseData = new ResponseData<>();

        if (updateCartNumResponse == null) {
            return new ResponseUtil<String>().setErrorMsg("操作失败，请刷新页面重试");
        }
        responseData.setCode(200);
        responseData.setMessage(updateCartNumResponse.getMsg());
        responseData.setResult("成功");
        responseData.setTimestamp(System.currentTimeMillis());
        responseData.setSuccess(true);

        return responseData;
    }


    /**
     * 接口文档有问题，
     * 该接口是删除选中的商品
     */
    @DeleteMapping("carts/{uid}/{pid}")
    public ResponseData deleteCartItem(@PathVariable("uid") Long uid, @PathVariable("pid") Long pid) {
        DeleteCartItemRequest request = new DeleteCartItemRequest();
        request.setItemId(pid);
        request.setUserId(uid);


        service.deleteCartItem(request);

        ResponseData responseData = new ResponseUtil().setData("成功");
        responseData.setMessage("success");
        responseData.setTimestamp(System.currentTimeMillis());
        return responseData;
    }

    /***
     *  该接口是删除用户所有商品
     * @param userId: 用户ID
     */
    @DeleteMapping("items/{uid}")
    public ResponseData deleteUserCart(@PathVariable("uid") Long userId) {
        DeleteCheckedItemRequest request = new DeleteCheckedItemRequest();
        request.setUserId(userId);

        service.deleteCheckedItem(request);

        ResponseData responseData = new ResponseUtil().setData("成功");
        responseData.setMessage("success");
        responseData.setTimestamp(System.currentTimeMillis());
        return responseData;
    }

    /***
     *  全选购物车的内容
     * @param request :userId,checked[是否选中，没什么用，该接口是要全选]
     */
    @PutMapping("items")
    public ResponseData checkCartAllProduct(@RequestBody CheckAllItemRequest request) {

        CheckAllItemResponse result = service.checkAllCartItem(request);


        ResponseData response;
        if (result.getCode().equals("200")) {
            response = new ResponseUtil().setData("成功");
            response.setMessage("success");
            response.setTimestamp(System.currentTimeMillis());
        } else {
            response = new ResponseUtil().setErrorMsg(500, "请检查购物车");
            response.setMessage("fail");
            response.setTimestamp(System.currentTimeMillis());
        }

        return response;
    }
}
